﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NewsMine.DomainObjects;
using NewsMine.Storage;

namespace NewsDiscoveryEngine
{
    [Serializable]
    public class IndexHtmlFeedItemJob : BaseJob
    {
        public FeedItem FeedItemToIndex { get; set; }

        public override bool ExecuteJob()
        {
            if (this.FeedItemToIndex == null)
            {
                return false;
            }
            FeedIndexer.Instance.IndexFeedItem(this.FeedItemToIndex);
            base.ProcessOutput(true);
            return true;
        }

        public static void IndexFeedFromIndexQueue()
        {
            int count = 0;
            if (Defaults.IndexingQueue.GetCount() > 0)
            {
                List<FeedItem> feedItemsForIndexing = new List<FeedItem>();

                count = 0;

                while (Defaults.IndexingQueue.GetCount() > 0)
                {
                    count++;
                    object itemDequeued = Defaults.IndexingQueue.Dequeue();

                    if (itemDequeued == null)
                        continue;

                    if (!(itemDequeued is FeedItem))
                    {
                        throw new ArgumentException("FeedItem is expected in the indexing Queue, if some else queued, we cant process");
                    }

                    feedItemsForIndexing.Add((FeedItem)itemDequeued);

                    if (feedItemsForIndexing.Count > 1000)
                    {
                        FeedIndexer.Instance.IndexFeedItems(feedItemsForIndexing);

                        feedItemsForIndexing.Clear();
                    }
                }

                if (feedItemsForIndexing.Count > 0)
                {
                    FeedIndexer.Instance.IndexFeedItems(feedItemsForIndexing);
                }


            }

        }



        static string indexUpdatedTimeStampSettingsKey = "IndexHtmlFeedItemJob.LastIndexUpdatedTimeStampForUpdateIndex";
        public static void IndexFeedThatIsUpdatedInSqliteStore()
        {

            var result = Defaults.SettingsStore.Get(indexUpdatedTimeStampSettingsKey);


            long lastTimestampTicks = long.MinValue;

            if (result != null)
            {
                lastTimestampTicks = Convert.ToInt64(result);
            }

            var feedItemsForIndexing = FeedIndexSearcher.Instance.SQLiteFeedStoreHelper.GetFeedItemsBySqlQuery("select * from Feed where UpdatedDateTime>" + lastTimestampTicks.ToString() + " AND pubdate <> UpdatedDateTime  ");




            if (feedItemsForIndexing.Count > 0)
            {
                FeedIndexer.Instance.UpdateIndexWithFeedItems(feedItemsForIndexing);
            }


            Defaults.SettingsStore.Set(indexUpdatedTimeStampSettingsKey, DateTime.UtcNow.Ticks);
        }


    }
}
